package jnpf.message.service.impl.open;

import jnpf.base.service.BillRuleService;
import jnpf.constant.PermissionConst;
import jnpf.exception.DataException;
import jnpf.message.model.message.OpenBaseModel;
import jnpf.message.model.message.OpenDeptModel;
import jnpf.message.model.message.OpenGroupModel;
import jnpf.message.service.SynThirdInfoService;
import jnpf.message.service.ThirdOpenService;
import jnpf.message.util.SynThirdConsts;
import jnpf.permission.entity.GroupEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.service.GroupService;
import jnpf.permission.service.UserRelationService;
import jnpf.util.JsonUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
@RequiredArgsConstructor
public class ThirdOpenGroupServiceImpl implements ThirdOpenService {

	private final SynThirdInfoService synThirdInfoService;

	private final UserProvider userProvider;

	private final UserRelationService userRelationService;

	private final GroupService groupService;

	private final BillRuleService billRuleService;

	private static final String BILL_CODE = "group";

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object beforeProcess(OpenBaseModel openBaseModel, Map<String, OpenDeptModel> organizeMap) {
		OpenGroupModel groupModel = (OpenGroupModel) openBaseModel;
		OpenBaseModel.OperationType operationType = groupModel.getType();
		String description = "";
		String groupId = groupModel.getGroupId();
		try {
			switch (operationType) {
				case ADD:
				case EDIT:
					GroupEntity groupEntity = groupService.getInfo(groupId);
					if (groupEntity != null) {
						//删除员工分组关系
						userRelationService.deleteAllByObjId(groupEntity.getId());
					}
					return groupModel;
				case DELETE:
					GroupEntity group = groupService.getInfo(groupId);
					if (group != null) {
						//删除员工分组关系
						userRelationService.deleteAllByObjId(group.getId());
						//删除分组
						groupService.delete(group);
					}
			}
		} catch (Exception e) {
			description = e.getMessage();
			log.error("分组同步beforeProcess error  message -> {} stack -> {}", JsonUtil.getObjectToString(openBaseModel), e);
			// throw e;
		} finally {
			saveSynThirdInfoEntity(operationType, SynThirdConsts.DATA_TYPE_GROUP, groupId, StringUtils.isBlank(description) ? 2 : 1, description, synThirdInfoService, userProvider);
		}
		return null;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void afterProcess(List<Object> result) {
		//保存修改分组信息
		GroupEntity groupEntity = result.stream().map(e -> {
			OpenGroupModel groupModel = (OpenGroupModel) e;
			GroupEntity entity = new GroupEntity();
			entity.setId(groupModel.getGroupId());
			entity.setFullName(groupModel.getGroupName());
			// 将类型替换为companyId
			entity.setType(groupModel.getCompanyId());
			try {
				entity.setEnCode(billRuleService.getBillNumber(BILL_CODE, false));
			} catch (DataException ex) {
				log.error(ex.getMessage());
			}
			return entity;
		}).findFirst().get();
		groupService.saveOrUpdate(groupEntity);
		//保存分组关系
		List<UserRelationEntity> relationEntities = result.stream().map(e -> {
			OpenGroupModel groupModel = (OpenGroupModel) e;
			List<UserRelationEntity> entities = new LinkedList<>();
			groupModel.getUserIds().forEach(userId -> {
				UserRelationEntity userRelationEntity = new UserRelationEntity();
				userRelationEntity.setObjectId(groupEntity.getId());
				userRelationEntity.setUserId(userId);
				userRelationEntity.setObjectType(PermissionConst.GROUP);
				entities.add(userRelationEntity);
			});
			return entities;
		}).findFirst().get();
		userRelationService.saveBatch(relationEntities);
	}
}
